package com.test.cofig;

import com.alibaba.fastjson2.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.NamedThreadLocal;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class TrafficRedrectUtil {

    /**
     *  路由表
     *  如果需要支持多线程 传播 参考我的帖子 ：https://blog.csdn.net/qq_36776608/article/details/142889577 怎么传播
     */
    private final static  ThreadLocal<Map<String,String>> TRAFFIC_ROUTE_TABLE = new NamedThreadLocal<>("TRAFFIC_ROUTE_TABLE");
    public final static String TRAFFIC_ROUTE_KEY = "TRAFFIC_ROUTE_KEY";


    private static Boolean IS_OPEN = null;

    public static boolean  isOpen(){
        if(Objects.isNull(IS_OPEN)){
            synchronized (TrafficRedrectUtil.class){
                if(Objects.nonNull(IS_OPEN)){
                    return IS_OPEN ;
                }
                String dev = "0" ;
                IS_OPEN = false;
                if(dev.equals(System.getProperty("open.TrafficRedrect"))){
                    IS_OPEN =true;
                }
            }
        }
        return IS_OPEN ;
    }

    /**
     *  添加路由！ 一个列表 原始服务名到新名字的说明
     *  例如 [  {"name":"服务1","dst":"服务1-开发张三丰"} ,{"name":"服务2","dst":"服务2-开发李四"}]
     *  不要代理太多了哦 这玩意 本来就是为了蹭环境服务器资源我本地可以少启动几个应用！ 加太多了如果head太大报错就尴尬了
     * @param rule
     */
    public static void addRoute(String rule){
        if(StringUtils.isBlank(rule)){
            return;
        }
        Map<String,String> rout = new LinkedHashMap<>();
        List<FeignRouteVO> frv = JSON.parseArray(rule,FeignRouteVO.class);
        if(Objects.isNull(frv) || frv.size() ==0 ){
            return;
        }
        frv.forEach(t->rout.put(t.getName(),t.getDst()));
        rout.put(TRAFFIC_ROUTE_KEY,rule);
        cleanRoute();
        TRAFFIC_ROUTE_TABLE.set(rout);
    }

    public static void addRoute(HttpServletRequest req){
        if(Objects.isNull(req) || StringUtils.isBlank(req.getHeader(TRAFFIC_ROUTE_KEY))){
            return;
        }
        addRoute(req.getHeader(TRAFFIC_ROUTE_KEY));
    }


    public static String getKey(String key){
        if(StringUtils.isBlank(key) || Objects.isNull(TRAFFIC_ROUTE_TABLE.get())  ){
            return null;
        }
        return TRAFFIC_ROUTE_TABLE.get().get(key);
    }
    public static void cleanRoute(){
        TRAFFIC_ROUTE_TABLE.remove();
    }

    public static void addRouteTab(Map<String, Collection<String>> head ){
        if(!head.containsKey(TRAFFIC_ROUTE_KEY) && StringUtils.isNotBlank(TRAFFIC_ROUTE_TABLE.get().
                get(TRAFFIC_ROUTE_KEY))){
            head.put(TRAFFIC_ROUTE_KEY,Arrays.asList(TRAFFIC_ROUTE_TABLE.get().get(TRAFFIC_ROUTE_KEY)));
        }
    }
}
